package com.chenjiagou.flight.controller;

import com.chenjiagou.flight.model.Flight;
import com.chenjiagou.flight.service.FlightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/flights")
public class FlightController {

    @Autowired
    private FlightService flightService;

    @GetMapping
    public ResponseEntity<Page<Flight>> getAllFlights(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "5") int size) {
        Pageable pageable = PageRequest.of(page, size);
        return ResponseEntity.ok(flightService.getAllFlights(pageable));
    }

    @GetMapping("/{id}")
    public ResponseEntity<Flight> getFlightById(@PathVariable Long id) {
        return flightService.getFlightById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/airports")
    public ResponseEntity<List<String>> getAirports() {
        List<String> airports = flightService.getAllAirportNames();
        return ResponseEntity.ok(airports); // 确保返回的是 List<String>
    }

    // 新增搜索接口
    @GetMapping("/search")
    public ResponseEntity<List<Flight>> searchFlights(
            @RequestParam(required = false) String depAirport,
            @RequestParam(required = false) String arrAirport) {
        List<Flight> flights = flightService.searchFlights(depAirport, arrAirport);
        return ResponseEntity.ok(flights);
    }

    @PostMapping
    public ResponseEntity<Void> addFlight(@RequestBody Flight flight) {
        try {
            flightService.addFlightWithSeats(flight); // 调用新增方法
            return ResponseEntity.created(null).build(); // 返回 HTTP 201 Created
        } catch (Exception e) {
            return ResponseEntity.badRequest().build(); // 返回 HTTP 400 Bad Request
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteFlight(@PathVariable Long id) {
        try {
            flightService.deleteFlight(id);
            return ResponseEntity.noContent().build(); // 返回 HTTP 204
        } catch (Exception e) {
            return ResponseEntity.notFound().build(); // 返回 HTTP 404
        }
    }

    // 新增更新接口
    @PutMapping("/{id}")
    public ResponseEntity<Void> updateFlight(@PathVariable Long id, @RequestBody Flight flight) {
        try {
            flight.setId(id);
            flightService.updateFlight(flight);
            return ResponseEntity.ok().build(); // 返回 HTTP 200
        } catch (Exception e) {
            return ResponseEntity.notFound().build(); // 返回 HTTP 404
        }
    }
}